<template>
  <div class="chat">
    <div class="chat-content" ref="chatContent">
      <div>
        <div
          class="chat-message"
          :class="{right: item.type === 'right'}"
          v-for="(item, idx) in messageList" :key="idx"
        >
          {{item.value}}
        </div>
      </div>
    </div>
    <div class="chat-footer">
      <button @click="leftSendMessage">发送左边的消息</button>
      <button @click="rightSendMessage">发送右边的消息</button>
    </div>
  </div>
</template>

<script>
import BScroll from '@better-scroll/core';

export default {
  data() {
    return {
      messageList: [],
    };
  },
  mounted() {
    this.scroller = new BScroll(this.$refs.chatContent);
  },
  watch: {
    'messageList.length': {
      // eslint-disable-next-line
      handler: function(newValue, oldValue) {
        this.$nextTick(() => {
          this.scroller.refresh();
          this.scroller.scrollTo(0, this.scroller.maxScrollY);
        });
      },
    },
  },
  methods: {
    leftSendMessage() {
      this.messageList.push({
        type: 'left',
        value: Math.ceil(Math.random() * 100),
      });
    },
    rightSendMessage() {
      this.messageList.push({
        type: 'right',
        value: Math.ceil(Math.random() * 100),
      });
    },
  },
};
</script>

<style>
.chat-content {
  height: 80vh;
  width: 800px;
  border: 1px solid #e8e8e8;
  margin: 10px;
  overflow: hidden;
}

.chat-message {
  padding: 10px;
  margin: 10px;
  background-color: #f5f5f5;
  border-radius: 10px;
}

.chat-message.right {
  text-align: right;
}
</style>
